package com.example.questionsystem.modules.qu.util;


import org.docx4j.convert.out.HTMLSettings;
import org.docx4j.convert.out.html.HtmlExporterNG2;
import org.docx4j.model.structure.HeaderFooterPolicy;
import org.docx4j.model.structure.SectionWrapper;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.wml.*;
import org.docx4j.XmlUtils;
import org.docx4j.jaxb.Context;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.bind.JAXBElement;
import javax.xml.transform.stream.StreamResult;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.*;
import java.io.ByteArrayInputStream;

public class DocxProcessor {

    public static String processDocxToHtml(MultipartFile inputFile) throws Exception {
        // 1. 加载输入的DOCX文件
        WordprocessingMLPackage wordPackage = WordprocessingMLPackage.load(
            new ByteArrayInputStream(inputFile.getBytes())
        );
        
        // 2. 处理选项拆分
        splitOptions(wordPackage);

        // 3. 转换为HTML
        return convertToHtml(wordPackage);
    }



    private static void splitOptions(WordprocessingMLPackage wordPackage) throws Exception {
        List<Object> paragraphs = wordPackage.getMainDocumentPart().getContent();
        ObjectFactory factory = Context.getWmlObjectFactory();

        Pattern optionPattern = Pattern.compile(
                "([A-Z])" +
                        "([．\\.])" +
                        "((?:(?![A-Z][．\\\\.]).)+)"
        );

        for (int i = 0; i < paragraphs.size(); i++) {
            Object obj = paragraphs.get(i);
            if (!(obj instanceof P)) continue;

            P p = (P) obj;
            List<RunWithFormat> runs = extractRunsWithFormat(p);

            // 合并所有文本内容用于选项检测
            StringBuilder fullText = new StringBuilder();
            for (RunWithFormat run : runs) {
                fullText.append(run.text);
            }
            String paraText = fullText.toString();



            if (paraText.isEmpty()) {
                System.out.println("跳过空段落");
                continue;
            }

            List<Option> options = detectOptions(paraText, optionPattern);
            System.out.println("检测到选项数量: " + options.size());

            if (options.size() < 2) continue;

            List<Object> newParagraphs = new ArrayList<>();

            // 添加选项前的文本
            if (options.get(0).startIndex > 0) {
                String prefix = paraText.substring(0, options.get(0).startIndex).trim();
                if (!prefix.isEmpty()) {
                    System.out.println("添加前缀: " + prefix);
                    newParagraphs.add(createParagraphWithFormat(factory, prefix, p, runs, 0, options.get(0).startIndex));
                }
            }

            // 添加所有选项
            for (int optIndex = 0; optIndex < options.size(); optIndex++) {
                Option option = options.get(optIndex);
                System.out.println("添加选项: " + option.text);

                int start = option.startIndex;
                int end = option.endIndex;
                newParagraphs.add(createParagraphWithFormat(factory, option.text, p, runs, start, end));
            }

            // 添加选项后的文本
            int lastEnd = options.get(options.size() - 1).endIndex;
            if (lastEnd < paraText.length()) {
                String suffix = paraText.substring(lastEnd).trim();
                if (!suffix.isEmpty()) {
                    System.out.println("添加后缀: " + suffix);
                    newParagraphs.add(createParagraphWithFormat(factory, suffix, p, runs, lastEnd, paraText.length()));
                }
            }

            // 替换原始段落
            int index = paragraphs.indexOf(p);
            paragraphs.remove(index);
            for (int j = 0; j < newParagraphs.size(); j++) {
                paragraphs.add(index + j, newParagraphs.get(j));
            }
            i += newParagraphs.size() - 1;
        }
    }

    // 辅助类：带格式的文本段
    private static class RunWithFormat {
        String text;
        RPr rPr; // 原始格式属性

        RunWithFormat(String text, RPr rPr) {
            this.text = text;
            this.rPr = rPr;
        }
    }

    // 提取带格式的文本段
    private static List<RunWithFormat> extractRunsWithFormat(P paragraph) {
        List<RunWithFormat> runs = new ArrayList<>();
        for (Object content : paragraph.getContent()) {
            if (content instanceof R) {
                R run = (R) content;
                RPr rPr = run.getRPr();
                StringBuilder text = new StringBuilder();
                for (Object runContent : run.getContent()) {
                    if (runContent instanceof Text) {
                        text.append(((Text) runContent).getValue());
                    } else if (runContent instanceof JAXBElement) {
                        Object value = ((JAXBElement<?>) runContent).getValue();
                        if (value instanceof Text) {
                            text.append(((Text) value).getValue());
                        }
                    }
                }
                runs.add(new RunWithFormat(text.toString(), rPr));
            }
        }
        return runs;
    }

    // 创建带格式的段落
    private static P createParagraphWithFormat(ObjectFactory factory, String text, P source,
                                               List<RunWithFormat> originalRuns, int startIndex, int endIndex) {
        P newP = factory.createP();

        // 复制段落样式
        if (source.getPPr() != null) {
            newP.setPPr((PPr) XmlUtils.deepCopy(source.getPPr()));
        }

        // 创建新的Run并应用原始格式
        int currentIndex = 0;
        for (RunWithFormat run : originalRuns) {
            if (currentIndex >= endIndex) break;

            int runEnd = currentIndex + run.text.length();
            if (runEnd > startIndex) {
                // 计算当前run中需要复制的文本范围
                int copyStart = Math.max(startIndex, currentIndex) - currentIndex;
                int copyEnd = Math.min(endIndex, runEnd) - currentIndex;

                if (copyStart < copyEnd) {
                    String textToCopy = run.text.substring(copyStart, copyEnd);

                    // 创建新Run并应用原始格式
                    R newRun = factory.createR();
                    if (run.rPr != null) {
                        newRun.setRPr((RPr) XmlUtils.deepCopy(run.rPr));
                    }

                    Text newText = factory.createText();
                    newText.setValue(textToCopy);
                    newText.setSpace("preserve");
                    newRun.getContent().add(newText);

                    newP.getContent().add(newRun);
                }
            }
            currentIndex = runEnd;
        }

        return newP;
    }

    // 选项检测辅助类（保持不变）
    private static class Option {
        String text;
        int startIndex;
        int endIndex;

        Option(String text, int startIndex, int endIndex) {
            this.text = text;
            this.startIndex = startIndex;
            this.endIndex = endIndex;
        }
    }

    // 选项检测方法（保持不变）
    private static List<Option> detectOptions(String text, Pattern pattern) {
        List<Option> options = new ArrayList<>();
        Matcher matcher = pattern.matcher(text);

        int lastEnd = 0;
        while (matcher.find()) {
            String optionLetter = matcher.group(1);
            String separator = matcher.group(2);
            String content = matcher.group(3);

            String optionText = optionLetter + separator + content;

            int start = matcher.start();
            int end = matcher.end();

            options.add(new Option(optionText, start, end));
            lastEnd = end;
        }

        return options;
    }

    // 将Word文档转换为HTML
    private static String convertToHtml(WordprocessingMLPackage wordPackage) throws Exception {
        for (SectionWrapper section : wordPackage.getDocumentModel().getSections()) {
            HeaderFooterPolicy policy = section.getHeaderFooterPolicy();

            // 清除默认页眉
            if (policy.getDefaultHeader() != null) {
                policy.getDefaultHeader().getContent().clear();
            }

            // 清除默认页脚
            if (policy.getDefaultFooter() != null) {
                policy.getDefaultFooter().getContent().clear();
            }

        }
        // 2. 配置HTML设置
        HTMLSettings htmlSettings = new HTMLSettings();
        htmlSettings.setImageHandler(new WordToHtmlConverter.ServerImageHandler());
        htmlSettings.setImageDirPath(null);  // 禁用本地保存
        htmlSettings.setImageTargetUri(null); // 禁用相对路径

        // 3. 创建导出器
        HtmlExporterNG2 exporter = new HtmlExporterNG2();

        // 4. 执行转换
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        StreamResult streamResult = new StreamResult(outputStream);

        exporter.html(
                wordPackage,
                streamResult,
                htmlSettings
        );

        // 5. 返回HTML内容
        return outputStream.toString(StandardCharsets.UTF_8.name());
    }
}